import os
import re

from Server import const


def __getWorkPath() -> str:
    fp = os.path.realpath(__file__)
    workPath = os.path.dirname(fp).replace('\\', '/')
    if workPath[-1] == '/':
        workPath = workPath[:-1]
    return '/'.join(workPath.split('/')[:-1])


def __getParentPath(sonPath: str) -> [str, str]:
    sonPath = sonPath.replace('\\', '/')
    if sonPath[-1] == '/':
        sonPath = sonPath[:-1]
    end = 0
    for i in range(len(sonPath) - 1, -1, -1):
        if sonPath[i] == '/':
            end = i
            break
    return sonPath[:end], sonPath[end + 1:]
    # ll = 1 + len(sonPath.split('/')[-1])
    # return sonPath[:-1 * ll], curName


WORK = __getWorkPath()
ROOT = __getParentPath(WORK)[0]
DEF_RES = ROOT + '/resource'
PROXY_URL = '/'


def strReplaceX(text: str, replacements: dict) -> str:
    pattern = re.compile('|'.join(re.escape(old) for old in replacements.keys()))
    return pattern.sub(lambda m: replacements[m.group(0)], text)


def getVariable(v: str) -> str:
    return eval(v[2:-1])


def translate(srcStr: str) -> str:
    varDict = {
        '${ROOT}': ROOT,
        '${WORK}': WORK,
        '${DEF_RES}': DEF_RES,
        '${PROXY_URL}': PROXY_URL
    }
    return strReplaceX(srcStr, varDict)


DefaultSubRoutes = [
    {
        "route": const.IconRoute,
        "path": translate("${DEF_RES}/icon")
    },
    {
        "route": const.JsRoute,
        "path": translate("${DEF_RES}/js")
    },
    {
        "route": const.CssRoute,
        "path": translate("${DEF_RES}/css")
    }
]
